<?php
/**
 *
 * Author:苏光盼
 * Date:2020/6/22 下午10:31
 * Class:RoleMenu.php
 * Web:https://app.admin.suanzisu.com
 * Project:通用APP后台管理系统
 *
 */

namespace App\HttpController\Admin;


use App\Logic\RoleMenu as LogicRoleMenu;
use App\Util\Common;
use EasySwoole\Http\Exception\Exception as HttpExc;
use EasySwoole\ORM\Exception\Exception;

class Role_menu extends Base
{
    final public function index()
    {
        $data =  LogicRoleMenu::list($this->request(), 100);
        return $this->lay($data['data'],$data['rows']);
    }

    /**
     * @return mixed
     * 保存某个菜单
     * @throws Exception
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \Throwable
     */
    final public function save()
    {
        $data = $this->request()->getParsedBody('data');
        if( $data ){
            $ret = LogicRoleMenu::updateOrInsert($data);
            if($ret){
                return $this->success(['data'=>$ret],'菜单更新成功！');
            }
            throw new HttpExc('save data fail', 403);
        }
        throw new HttpExc('the args is empty',403);
    }

    /**
     * 根据当前用户的组ID
     * 更新后台的用户组左侧菜单
     * @throws Exception
     * @throws \Throwable
     */
    public function clear()
    {
        $md5_uid = $this->request()->getHeaderLine('x-token');
        $group_id = \App\Logic\Login::getUserData($md5_uid,'group_id');
        if(!$group_id) throw new HttpExc('没有获取到当前用户的组ID',403);
        $menu  = LogicRoleMenu::findGroupMenu($group_id);
        $data = Common::create_menu($menu);
        return $this->success($data);
    }

    public function edit(){
        $id = Common::check($this->request());
        $data['all_data'] = LogicRoleMenu::findByTree();
        $data['find_data'] = \App\Model\RoleMenu::create()->get($id);
        $this->success($data);
    }

    /**
     * @return mixed
     * 获取树形式的左侧菜单
     * @throws Exception
     * @throws \Throwable
     */
    public function find_tree(){
        return $this->success(LogicRoleMenu::findByTree());
    }

    public function del()
    {
        $id = Common::check($this->request(),'id');
        $mode = \App\Model\RoleMenu::create()->get($id);
        $mode->destroy();
        $this->success();
    }

}